package org.goodsl.mdd.validator;

import org.goodsl.mdd.Seg;
import org.goodsl.mdd.SingleValidResult;
import org.goodsl.mdd.Validator;

import java.net.MalformedURLException;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-11-14
 * Time: 上午8:52
 * To change this template use File | Settings | File Templates.
 */
public class UrlValidator extends Validator<Seg> {

    private String protocol;
    private String host;
    private int port = -1;

    public UrlValidator(String message) {
        this(null, null, -1, message);
    }

    public UrlValidator(String protocol, String host, int port, String message) {
        super(message);
        this.protocol = protocol;
        this.host = host;
        this.port = port;
    }

    public UrlValidator(String protocol, String message) {
        this(protocol, null, -1, message);
    }

    @Override
    public SingleValidResult<Seg> verify(Seg variable) {

        String urlStr = variable.getValue().toString();
        java.net.URL url;
        boolean valid = false;
        try {
            url = new java.net.URL(urlStr);
            valid = true;
            if (protocol != null && protocol.length() > 0 && !url.getProtocol().equals(protocol))
                valid = false;
            if (host != null && host.length() > 0 && !url.getHost().equals(host))
                valid = false;
            if (port != -1 && url.getPort() != port)
                valid = false;


        } catch (MalformedURLException e) {
            valid = false;
        }

        if (valid)
            return new SingleValidResult<Seg>(true, "", variable, this);
        else
            return new SingleValidResult<Seg>(false, getMessage(), variable, this);
    }

}
